<template>
  <q-page class="q-pa-md wrapBox">
    <div v-loading="loading">
      <div class="nav">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item>
            <el-image src="/svgs/modelApplication.svg" style="width: 17px;margin-top: 2px" fit />
          </el-breadcrumb-item>
          <el-breadcrumb-item>模型服务</el-breadcrumb-item>
          <el-breadcrumb-item><span style="color: #333;">训练作业</span></el-breadcrumb-item>
        </el-breadcrumb>
      </div>
      <div class="datasetBox" style="position: relative">
        <div class="contentBox_title">
          <span>训练作业</span>
        </div>
        <div class="contentBox">
          <div class="searchWrap" style="margin-top: 10px">
            <div>
              <el-input
                v-model.trim="searchName"
                placeholder="搜索训练任务名称或描述"
                spellcheck="false"
              >
                <template #prepend>
                  <el-select v-model="typeValue" placeholder="全部" style="width: 120px;background-color: #fff">
                    <el-option
                      v-for="item in modelStatusList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                    />
                  </el-select>
                </template>
                <template #append>
                  <el-button :icon="Search" @click="getDataList" />
                </template>
              </el-input>
            </div>
            <div>
              <el-button
                type="primary"
                size="default"
                @click="toCreatePage"
              >新增</el-button>
            </div>
          </div>
          <el-table
            :data="filterTableData"
            stripe
            style="width: 100%;margin-top: 15px"
            :header-cell-style="{ background: '#eee', color: '#333333' }"
          >
            <el-table-column align="center" prop="title" label="名称" width="180">
              <template #default="scope">
                <el-button link type="primary" @click="toDetailPage(scope.row.model_id, scope.row.id)">{{ scope.row.title }}</el-button>
              </template>
            </el-table-column>
            <el-table-column align="center" prop="status" label="训练状态" width="180" />
            <el-table-column align="center" label="作业类型" width="140">训练作业</el-table-column>
            <el-table-column align="center" prop="creator_username" label="创建人" />
            <el-table-column align="center" prop="create_at" label="创建时间" />
            <el-table-column align="center" prop="model_title" label="算法" />
            <el-table-column align="center" prop="labels" label="操作">
              <template #default="scope">
                <el-button
                  v-show="userStatus?true:scope.row.creator_username == userInfoName"
                  link type="primary" size="small"
                  @click="openDeleteBox(scope.row.model_id, scope.row.id)">删除</el-button>
                <el-button
                  v-show="userStatus?true:scope.row.creator_username == userInfoName"
                  link type="primary"
                  :disabled="(scope.row.status == 'success' || scope.row.status == 'fail') ? true : false" size="small"
                  @click="scope.row.status == 'running' ? stopRunsFun(scope.row.id) : ''">停止</el-button>
                <!-- 暂时不需要复用功能，不确定后期是否需要 -->
                <!-- <el-button link type="primary" size="small">复用</el-button> -->
              </template>
            </el-table-column>
          </el-table>
        </div>
        <div class="row" style="justify-content: end;margin-top: 20px;" v-if="filterTableData.length > 0">
          <el-pagination
            background
            layout="prev, pager, next, sizes, jumper"
            :total="labelAssignData.count"
            :page-sizes="[10, 20, 50]"
            @size-change="sizeChange"
            :current-page="pageData.page"
            @current-change="changePage"
          />
        </div>
      </div>
    </div>
    <q-dialog v-model="dialogDeleteData">
        <q-card style="width: 350px;">
          <q-card-section>
            <div class="text-h6" style="font-size: 17px;">
              <el-icon
                style="color: #ff5656;display: inline-block;vertical-align: middle;margin-top: -3px;font-size: 20px;">
                <WarningFilled />
              </el-icon>
              删除提示
            </div>
          </q-card-section>
          <q-card-section class="q-pt-none">
            <div>确定删除本条数据吗？</div>
            <div>删除后不可恢复，请谨慎操作！</div>
          </q-card-section>
          <q-card-actions align="right" class="text-primary">
            <el-button v-close-popup style="background-color: #FFFFFF">取消</el-button>
            <el-button type="primary" @click="deleteData">确认删除</el-button>
          </q-card-actions>
        </q-card>
      </q-dialog>
  </q-page>
</template>

<script setup lang="ts">
import { ref, computed, shallowRef,onMounted } from "vue";
import { useRouter } from 'vue-router';
import { getAllRunsList, deleteRuns, stopRuns } from 'src/api/model'
import { Search } from '@element-plus/icons-vue'
const userStatus = JSON.parse(localStorage.getItem('user') || "{}").status;//判断用户是否是项目创建人或项目管理员
const userInfoName = localStorage.getItem('username')//获取用户登录的用户名
import { ElNotification, ElMessageBox, ElMessage } from 'element-plus'
const router = useRouter()
const projectId = router.currentRoute.value.params.project_id
const loading = ref(false)
const searchName = ref('')
const dialogDeleteData = ref(false)
import { modelStore } from 'src/stores/model';
import { dataSetStore } from 'src/stores/dataSet';
const store=dataSetStore()
const typeValue = ref('');
import { modelStatusList } from 'src/utils/useData';
const labelAssignData = shallowRef(
  {
    "count": 0,
    "next": "",
    "previous": "",
    "results": [
      {
        "id": 0,
        "title": "",
        "status": "",
        "git_vendor": "",
        "creator_username": "",
        "git_uri": "string",
        "create_at": "",
        "description": "string"
      },
    ]
  }
)
const pageData = dataSetStore().pageData;
function sizeChange(pageSize:any) {
  dataSetStore().setPageData(1);
  dataSetStore().setPageSizeData(pageSize);
  getDataList()
}
function changePage(currentPage:any){
  dataSetStore().setPageData(currentPage);
  getDataList()
}
const runId = ref()
const modelId = ref()
const filterTableData = computed(() =>
  labelAssignData.value.results.filter(
    (data) =>
      !searchName.value ||
      data.title.toLowerCase().includes(searchName.value.toLowerCase()) ||
      data.id.toString().toLowerCase().includes(searchName.value.toLowerCase())

  )
)
onMounted(() => {
  // 通过store.quickStart.quickFlow判断是否显示快速入门提示
  if (store.quickStart.quickFlow) {
    store.setQuickStart({
      tipsPopup: true,
      quickFlow: true,
      flowNumber: store.quickStart.flowNumber
    })
  }
})
getDataList()
function getDataList() {
  loading.value = true;
  let obj:any = {}
  if( typeValue.value != '' ) obj.status = typeValue.value;
  if( searchName.value != '' ) obj.keyword = searchName.value;
  obj = Object.assign(obj, pageData);
  getAllRunsList(projectId,obj).then((res: any) => {
    labelAssignData.value = res.data;
  }).finally(() => {
    loading.value = false
  })
}
function toCreatePage() {
  modelStore().setShowModelId(0);
  router.push({ name: 'model-manage-create', params: { project_id: projectId } })
}

// 确认删除弹窗
function openDeleteBox(model_id: number, run_id: number) {
  runId.value = run_id
  modelId.value = model_id
  dialogDeleteData.value = true
}
function deleteData() {
  dialogDeleteData.value = false
  deleteRuns(projectId, modelId.value, runId.value).then((res: any) => {
    ElNotification({
      title: 'Success',
      message: '删除成功',
      type: 'success',
    })
  }).finally(() => {
    getDataList()
  }).catch((error) => {
    console.log(error)
  })
}
function toDetailPage(model_id: number, run_id: number) {
  const dataSetObj = modelStore()
  dataSetObj.dataset(model_id)
  dataSetObj.dataRunsIdset(run_id)
  router.push({ name: 'runs-detail', query: { project_id: projectId } })
}
function stopRunsFun(run_id: number) {
  ElMessageBox.confirm('确定停止该训练任务吗？', '停止任务', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    stopRuns(projectId, run_id).then(() => {
      ElMessage.success('停止训练成功！')
      getDataList()
    }).finally(() => {
      loading.value = false
    })
  }).catch(() => {
    console.log('cancel delete')
  })
}
</script>

<style scoped lang="scss">
.wrapBox {
  padding: 0 !important;
  .nav {
    display: flex;
    align-items: center;
    padding-left: 20px;
    cursor: pointer;
    background-color: var(--nav-bg-color);
    height: 46px;
    ::v-deep .el-breadcrumb{
      display: flex;
      align-items: center;
    }
  }
  .datasetBox {
    margin: 0 20px;
    .contentBox_title{
      position: relative;
      display: flex;
      align-items: center;
      color: var(--title);
      font-weight: 500;
      font-size: 16px;
      padding: 15px 15px;
      border-bottom: 1px solid #e5e6eb;
      background-color: #ffffff !important;
      .icon{
        position: absolute;
        left: 90px;
        top: 22px;
        width: 17px;
      }
      .text{
        position: absolute;
        left: 104px;
        top: 19px;
        font-size: 12px;
        color: #3d5ce4;
        font-weight: 400;
        cursor: pointer;
      }
    }
    .contentBox {
      padding: 12px;
      background-color: #ffffff !important;
      .searchWrap{
        display: flex;
        justify-content: space-between;
      }
    }
  }
}
//输入框placeholder样式
::v-deep .el-input__inner {
  &::placeholder {
    color: #ccc;
    font-size: 14px;
  }
  &::-webkit-input-placeholder {
    /* WebKit browsers 适配谷歌 */
    color: #ccc;
    font-size: 14px;
  }
  &:-moz-placeholder {
    /* Mozilla Firefox 4 to 18 适配火狐 */
    color: #ccc;
    font-size: 14px;
  }
  &::-moz-placeholder {
    /* Mozilla Firefox 19+ 适配火狐 */
    color: #ccc;
    font-size: 14px;
  }
  &:-ms-input-placeholder {
    /* Internet Explorer 10+  适配ie*/
    color: #ccc;
    font-size: 14px;
  }
}
//点击下拉框，去掉输入框蓝色高亮显示
:deep(.el-input){
  --el-input-focus-border:#fff;
  --el-input-transparent-border: 0 0 0 0px;
  --el-input-border-color:var(--el-border-color);
  --el-input-hover-border:0px !important;
  --el-input-hover-border-color:var(--el-border-color);
  --el-input-focus-border-color:var(--el-border-color);
  --el-input-clear-hover-color:var(--el-border-color);
}
</style>
